﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using spbtzb;
using System.Data.OleDb;

public partial class Back_MenuManage : System.Web.UI.Page
{
    protected String StrConn = ConString.ConnString;
    private Boolean session_Logined
    {
        set
        {
            Session["Logined"] = value;
        }
        get
        {
            return Session["Logined"] == null ? false : Convert.ToBoolean(Session["Logined"]);
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (session_Logined == false)
            {
                Response.Redirect("Login.aspx?ErrorMessage=" + "您未登录，请在此登录");
            }
            this.Page.Title = "栏目管理页面";
            BindMenus();
        }
        
        gv_ChildMenuList.RowEditing  += new GridViewEditEventHandler(gv_ChildMenuList_RowEditing);
        gv_ChildMenuList.RowCancelingEdit  += new GridViewCancelEditEventHandler(gv_ChildMenuList_RowCancelingEdit);
        gv_ChildMenuList.RowUpdating  += new GridViewUpdateEventHandler(gv_ChildMenuList_RowUpdating);
    }
    protected void BindMenus()
    {
        string sqlCmd = "SELECT TypeName, TypeCode FROM ContentType WHERE ParentType = 'NO' OR ParentType = 'STBB'";
        DataTable dtTypes = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);
        this.ddlMenus.DataSource = dtTypes;
        this.ddlMenus.DataTextField = "TypeName";
        this.ddlMenus.DataValueField = "TypeCode";
        this.ddlMenus.DataBind();
        ViewState["ParentType"] = this.ddlMenus.SelectedValue;
        BindControl();
    }

    protected void ddlMenus_SelectedIndexChanged(object sender, EventArgs e)
    {
        ViewState["ParentType"] = ddlMenus.SelectedValue;
        BindControl();
    }
    protected void BindControl()
    {
        string parentType = ViewState["ParentType"].ToString();
        string sqlCmd = "SELECT ID,TypeName, TypeCode  FROM ContentType WHERE ParentType = '" + parentType + "'";
        DataTable dtTypes = AccessHelper.ExecuteDataTable(StrConn, System.Data.CommandType.Text, sqlCmd);
        
        gv_ChildMenuList.DataSource = dtTypes;
        gv_ChildMenuList.DataBind();
    }

    protected void gv_ChildMenuList_RowEditing(object sender, GridViewEditEventArgs e)
    {
        gv_ChildMenuList.EditIndex = e.NewEditIndex;
        Button btn = ((Button)gv_ChildMenuList.Rows[e.NewEditIndex].FindControl("btnDelete"));
        
        BindControl();
    }
    protected void gv_ChildMenuList_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
    {
        gv_ChildMenuList.EditIndex = -1;
        BindControl();
    }
    protected void gv_ChildMenuList_RowUpdating(object sender, GridViewUpdateEventArgs e)
    {
        string typeCode = (((TextBox)(gv_ChildMenuList.Rows[e.RowIndex].Cells[0].Controls[0])).Text.ToString().Trim());
        string typeName = (((TextBox)(gv_ChildMenuList.Rows[e.RowIndex].Cells[1].Controls[0])).Text.ToString().Trim());
        string id = gv_ChildMenuList.DataKeys[e.RowIndex].Value.ToString();

        //string checkSqlCmd = string.Format("SELECT ID FROM ContentType WHERE typeCode  = '" + typeCode + "'");
        //Object obj = AccessHelper.ExecuteScalar(StrConn, CommandType.Text, checkSqlCmd);
        string sqlCmd = string.Format("SELECT TypeCode FROM ContentType WHERE ID = {0}", id);
        Object obj = AccessHelper.ExecuteScalar(StrConn, CommandType.Text, sqlCmd);
       
        /*当前栏目的编码被修改*/
        if(!obj.ToString().Equals(typeCode))
        {
            string checkSqlCmd = string.Format("SELECT ID FROM ContentType WHERE typeCode  = '" + typeCode + "'");
            Object newObj = AccessHelper.ExecuteScalar(StrConn, CommandType.Text, checkSqlCmd);
            
            //如果newObj不等于空，说明此栏目编码已被其他栏目所使用
            if (newObj != null)
            {
                ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "update", "alert('此栏目编码已经存在！');", true);
                return;
            }
            else
            {
                if (UpdateContentType(typeCode, typeName, id))
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "update", "alert('栏目更新成功！');", true);
                    gv_ChildMenuList.EditIndex = -1;
                    BindControl();
                    return;
                }
                else
                {
                    ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "update", "alert('栏目更新失败,请联系管理员！');", true);
                    return;
                }
            }
        }

        sqlCmd = string.Format("Update ContentType SET TypeCode = '{0}', TypeName = '{1}' WHERE ID = {2}",
                         typeCode, typeName, id);
        int iRet = AccessHelper.ExecuteNonQuery(StrConn, CommandType.Text, sqlCmd);
        if (iRet != 1)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "update", "alert('栏目更新失败,请联系管理员！');", true);
            return;
        }
        gv_ChildMenuList.EditIndex = -1;
        ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "update", "alert('栏目更新成功！');", true);
        BindControl();

        Common.UpdateCacheFromDB();
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        string typeName = txtTypeName.Text.Trim();
        string typeCode = txtTypeCode.Text.Trim();
        if (typeName.Equals(""))
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "add", "alert('栏目编码不能为空！');", true);
            dvChildMenu.Style.Clear();
            return;
        }
        if (typeCode.Equals(""))
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "add", "alert('栏目名称不能为空！');", true);
            dvChildMenu.Style.Clear();
            return;
        }
        string checkSql = string.Format("SELECT ID FROM ContentType WHERE TypeCode = '{0}'",typeCode);
        if (AccessHelper.ExecuteScalar(StrConn, CommandType.Text, checkSql) != null)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "add", "alert('此栏目编号已经存在！');", true);
            dvChildMenu.Style.Clear();
            return;
        }
        string parentType = ViewState["ParentType"].ToString();

        string strSingle = "0";
        if (CheckBox1.Checked)
        {
            strSingle = "1";
        }
        

        string sqlCmd = string.Format("INSERT INTO ContentType (TypeCode,TypeName,ParentType,IsSingle) " +
                        "VALUES ('{0}','{1}','{2}','{3}')",
                         typeCode, typeName, parentType, strSingle);
        int iRet = AccessHelper.ExecuteNonQuery(StrConn, CommandType.Text, sqlCmd);

        if (CheckBox1.Checked)
        {

            

            DataTable dataTable = AccessHelper.ExecuteDataTable(StrConn, CommandType.Text, "select max(ID) AS S from ContentType");
            int TypeID = int.Parse(dataTable.Rows[0]["S"].ToString());
            int ID = 0;

            sqlCmd = String.Format("INSERT INTO Contents (TypeCode, Title, Content, CreateTime) "
                       + "values ('{0}', '{1}', '{2}', '{3}' )", "1",
                       typeName, typeName, DateTime.Now.ToString());
            iRet = AccessHelper.ExecuteNonQuery(StrConn, System.Data.CommandType.Text, sqlCmd);

            dataTable = AccessHelper.ExecuteDataTable(StrConn, CommandType.Text, "select max(ID) AS S from Contents");
            ID = int.Parse(dataTable.Rows[0]["S"].ToString());

            string sqlCmd1 = String.Format("Insert into ContentAndType (ContentID,TypeID,ContentType) values('{0}','{1}','{2}')", ID, TypeID, typeCode);
            AccessHelper.ExecuteNonQuery(StrConn, CommandType.Text, sqlCmd1);

        }

        if (iRet != 1)
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "add", "alert('新栏目添加失败,请联系管理员！');", true);
            dvChildMenu.Style.Clear();
            return;
        }
        ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "add", "alert('新栏目添加成功！');", true);
        dvChildMenu.Style.Clear();
        BindControl();

        Common.UpdateCacheFromDB();
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        // 获取当前选择的index
        Button btn = (Button)sender;
        DataControlFieldCell dv = (DataControlFieldCell)btn.Parent;
        GridViewRow gvr = (GridViewRow)dv.Parent;
        int index = gvr.RowIndex;

        GridView gv = (GridView)gvr.Parent.Parent; // GridViewRow的Parent是GridView.ChildTable

        DataKeyArray dkCol = gv.DataKeys;
        int id = Convert.ToInt32(dkCol[index].Value);
        if (id < 0)
        {
            //RegisterClientScriptBlock("remind", "<script type='text/javascript'>alert('删除操作失败,请联系管理员！');</script>");
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('栏目删除操作失败,请联系管理员！');", true);
            return;
        }

        if (DeleteContentType(id.ToString()))
        {

            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('栏目删除操作成功！');", true);
           
        }
        else
        {
            ScriptManager.RegisterStartupScript(UpdatePanel1, Page.GetType(), "deletesuccess", "alert('栏目删除操作失败,请联系管理员！');", true);
            return;
        }
      
       
        BindControl();

        Common.UpdateCacheFromDB();
    }

    protected void btnCancel_Click(object sender, EventArgs e)
    {
        gv_ChildMenuList.ShowFooter = false;
        BindControl();
    }
    /*Debug*/
    public bool UpdateContentType(string typeCode, string typeName, string id)
    {
        String strCmd1 = string.Format("Update ContentType Set TypeCode = '{0}', TypeName = '{1}' " +
                         " WHERE ID = {2}",typeCode,typeName,id);

        String strCmd2 = string.Format("Update Contents Set TypeCode = '{0}' WHERE  TypeCode = (SELECT TypeCode FROM ContentType WHERE ID = {1})"
                          , typeCode, id);        

        OleDbConnection conn = new OleDbConnection(StrConn);
        OleDbTransaction transaction = null;
        bool flag = false;
        try
        {
            conn.Open();
            transaction = conn.BeginTransaction();

            OleDbCommand typeCommand = new OleDbCommand(strCmd1, conn, transaction);
            typeCommand.ExecuteNonQuery();

            OleDbCommand contentCommand = new OleDbCommand(strCmd2, conn,transaction);
          
            contentCommand.ExecuteNonQuery();



            transaction.Commit();
            flag = true;
        }
        catch (Exception ex)
        {
            flag = false;
            transaction.Rollback();
        }
        finally
        {
            conn.Close();
            conn.Dispose();
        }
        return flag;
    }

    public bool DeleteContentType(string id)
    {
        String strCmd1 = string.Format("DELETE FROM ContentType WHERE ID = {0}" , id);

        String strCmd2 = string.Format("DELETE FROM Contents WHERE TypeCode = (SELECT TypeCode FROM ContentType WHERE ID = {0})",id);

        OleDbConnection conn = new OleDbConnection(StrConn);
        OleDbTransaction transaction = null;
        bool flag = false;
        try
        {
            conn.Open();
            transaction = conn.BeginTransaction();

            OleDbCommand contentCommand = new OleDbCommand(strCmd2, conn, transaction);
            contentCommand.ExecuteNonQuery();

            OleDbCommand typeCommand = new OleDbCommand(strCmd1, conn,transaction);
            typeCommand.ExecuteNonQuery();

            transaction.Commit();
            flag = true;
        }
        catch (Exception ex)
        {
            flag = false;
            transaction.Rollback();
        }
        finally
        {
            conn.Close();
            conn.Dispose();
        }
        return flag;
    }
    /**/

}
